﻿@model RH.Web.ViewModels.UtilityModels.ListConfig
@using RH.Web.Utility;
@using RH.Common.Extensions;
@{
    String pageTitle = "Contact List";
    ViewBag.Title = Html.GetPageTitle(pageTitle);
    ListConfig config = RH.Web.ViewModels.UtilityModels.ListConfigBuilder.Build(
                @"{ ID | Name | UserName  }, 
                {Email | EmailOffice | Phone}",
                Model.DataSource, "/Private/Contact/Edit/{0}");
                //"javascript:void(0); MakeUser({0},'{1}')");
    ListConfig.Map(config, Model);
    String anchor = "<a class=\"btn btn-{0} btn-sm\" href=\"javascript:void(0);\" onclick=\"{1};\"><i class=\"glyphicon glyphicon-{2}\"></i> {3}</a>";
    Column editColumn = config.EditColumn;
    editColumn.Method = P =>
    {
        int id = RH.Common.DB.NullHandler.GetInt(P["ID"]);
        System.Text.StringBuilder sb = new System.Text.StringBuilder(10);        
        sb.AppendFormat(Model.DefaultEditAnchor, String.Format(Model.EditLinkFormat, id), String.Empty);
        sb.AppendFormat(anchor, "warning", String.Format("DeleteCinfrim({0}, this)", id), "remove", String.Empty);
        return MvcHtmlString.Create(sb.ToString());
    };

    Column makeUser = new Column("User Action",
    P =>
    {
        String name = RH.Common.DB.NullHandler.GetString(P["Name"]);
        int userID = RH.Common.DB.NullHandler.GetInt(P["UserID"]);
        int contactID = RH.Common.DB.NullHandler.GetInt(P["ID"]);
        if (userID > 0)
        {
            return MvcHtmlString.Create(
                String.Format(anchor, "default", String.Format("EditUser({0}, this)", userID), "edit", "Edit User")
                );
        }
        else
        {
            return MvcHtmlString.Create(
                String.Format(anchor, "primary", String.Format("MakeUser({0}, '{1}', this)", contactID, name.UrlEncode()), "edit", "Make User")
                );
        }
    }, null, null);
    
    Model.Columns.Add(makeUser);
                                
    if (UserInfo.IsCompanyUser) { 
        ViewData[AppConstants.ViewDataKeys.SELECTED_MENU] = CompanyMenu.Contacts;
    }
    if (Model.Pager == null) {
        Model.Pager = new PagerConfig(1, ConfigReader.pageSize, Model.DataSource.Rows.Count);
    }
}

<div class="rh-page-heading">
    <h1>@pageTitle</h1>
    <div>
        Add/Edit Contact or employee information of your company. Then give them access to add or edit projects in @ConfigReader.SiteName by adding them as a user of your company.
    </div>
</div>
<div class="rh-page-content">
    <div class="panel panel-success">
        <div class="panel-heading">
            <div class="pull-left"><h4>List of Company Contacts <span class="badge">@Model.Pager.TotalRecord</span></h4></div>
            <div class="pull-right"><a class="btn btn-success" href="@Url.PrivateUrl("Edit", "Contact")"><i class="glyphicon glyphicon-plus"></i> Add Contact</a></div>
            <div class="clearfix"></div>
        </div>
        <div class="panel-body">
            @*@Html.Partial("_ListView", Model)*@
            @Html.Partial("_DataTableList", Model)
        </div>
    </div>

    @*@Html.Partial("_DataTableList", Model)*@
    @*<a href="/Private/Contact/Edit">Add New Contact</a><br /><br />
    @Html.Partial("_ListView", ViewData[AppConstants.ViewDataKeys.LIST_CONFIG] as RH.Web.ViewModels.UtilityModels.ListConfig)*@
</div>

@*Make User Modal Start *@
<div class="modal fade" id="divMakeUserDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="userModalTitle">Manage Property Address</h4>
            </div>
            <div class="modal-body" id="divMakeUserDialog-body">
                <form id="frmCreateUser" method="post" action="/Private/Contact/CreateUser">
                    <input type="hidden" id="ID" name="ID" value="" />
                    <div class="col-md-7 rh-gridfix">
                        <div class="editor-label">
                            <label for="Email">User Name</label>
                        </div>
                        <div class="editor-field">
                            <input data-val="true" data-val-required="Please enter an User Name" data-val-length="The User Name must be at least 6 - 10 characters long."
                                   data-val-length-max="10" data-val-length-min="6" id="UserID" name="UserID" type="text" value="" />
                            <span class="field-validation-valid" data-valmsg-for="UserID" data-valmsg-replace="true"></span>
                        </div>
                    </div>
                    <div class="col-md-5 rh-gridfix">
                        <div class="editor-label">&nbsp;</div>
                        <div class="">
                            <label><input id="IsActive" name="IsActive" type="checkbox" value="" /> Is Active?</label>
                        </div>
                    </div>
                    <div class="clearfix"></div>

                    
                    <div class="editor-label">User Type</div>
                    <div class="">
                        <select id="GroupID" name="GroupID">
                            <option value="@ConfigReader.UserGroupIDOfCompanyUser">Standard User</option>
                            <option value="@ConfigReader.UserGroupIDOfCompanyAdmin">Admin User</option>
                        </select>
                    </div>                    


                    <div class="editor-label">
                        <label for="Password">Password</label>
                    </div>
                    <div class="editor-field">
                        <input data-val="true" data-val-length="The Password must be at least 6 characters long." data-val-required="Please Enter Password."
                               data-val-length-max="100" data-val-length-min="6" class="form-control" id="Password" name="Password" type="password" value="" />
                        <span class="field-validation-valid" data-valmsg-for="Password" data-valmsg-replace="true"></span>
                    </div>

                    <div class="editor-label">
                        <label for="ConfirmPassword">Confirm password</label>
                    </div>
                    <div class="editor-field">
                        <input data-val="true" data-val-equalto="The password and Confirm password do not match." data-val-required="Please Confirm your Password."
                               data-val-equalto-other="*.Password" class="form-control" id="ConfirmPassword" name="ConfirmPassword" type="password" value="" />
                        <span class="field-validation-valid" data-valmsg-for="ConfirmPassword" data-valmsg-replace="true"></span>
                    </div>
                    @*<div id="divSuccessMessage" style="display:none;"></div>*@                    
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="glyphicon glyphicon-off"></i> Close</button>
                <button type="button" class="btn btn-primary" onclick="MakeUser_Save();"><i class="glyphicon glyphicon-ok"></i> Save</button>
            </div>
        </div>
    </div>
</div>
@*Make User Modal End *@

@*Delete Dialog Modal Start *@
<div class="modal fade" id="deleteDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Delete Contact?</h4>
            </div>
            <div class="modal-body" id="deleteDialog-body">
                Do you really want to Delete this Contact?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> No</button>
                <button type="button" class="btn btn-primary" onclick="DeleteContact();"><i class="glyphicon glyphicon-ok"></i> Yes</button>
            </div>
        </div>
    </div>
</div>
@*Delete Dialog Modal End *@

@section JavaScriptPlaceHolder{
    @Scripts.Render(Bundles.jQueryValidate)
    <script language="javascript" type="text/javascript">
        var _ContactID = 0;
        var _SaveEdit = "";
        var _Anchor = null;
        //var _CategoryDialog = null;
        $(document).ready(function () {
            
        });
        function RemoveAlerts() {
            $('#divMakeUserDialog-body .alert-warning').remove();
            $('#divMakeUserDialog-body .alert-success').remove();
        }
        function EditUser(userID, anchor) {            
            RemoveAlerts();
            $('#ID').val(userID);
            PopulateUserInfo(userID);
            $('#divMakeUserDialog').modal('show');
            ShowLoadingAnimation(false);
        }
        function PopulateUserInfo(userID) {
            RemoveAlerts();
            Ajax('/Private/Contact/GetUserInfo/' + userID, null, function (result) {
                if (result.length <= 0)
                    $('#divMakeUserDialog-body').prepend(WarningMessageBox('Sorry! The requested user was not found for edit.'));
                else {
                    var user = eval('(' + result + ')');
                    $('#userModalTitle').html('Edit User Information');
                    $('#UserID').val(user.UserName);
                    $('#ID').val(user.ID);
                    $('#Password').val('');
                    $('#ConfirmPassword').val('');
                    $('#IsActive').prop('checked', user.IsActive);
                    $('#GroupID').val(user.GroupID);
                    $('#divMakeUserDialog').modal('show');
                }
                HideLoadingAnimation();
            });
        }
        function MakeUser(contactID, userName) {
            RemoveAlerts();
            userName = decodeURIComponent(userName).replace('+', ' ');
            _ContactID = contactID;
            $('#userModalTitle').html('Make <b>' + userName + '</b>, an user of @SessionCache.CurrentUser.Company.Name');
            $('#UserID').val('');
            $('#Password').val('');
            $('#ConfirmPassword').val('');
            $('#IsActive').prop('checked', true);
            $('#GroupID').val(@ConfigReader.UserGroupIDOfCompanyAdmin);
            $('#divMakeUserDialog').modal('show');            
        }

        function MakeUser_Save() {
            if ($('#frmCreateUser').valid()) {                
                var data = {ID: $('#ID').val(), UserName: $('#UserID').val(), Password: $('#Password').val(), ContactID: _ContactID };
                Ajax('@Url.PrivateUrl("CreateUser", "Contact")', data, function (result) {
                    RemoveAlerts();
                    if(result == -1)
                        $('#divMakeUserDialog-body').prepend(WarningMessageBox('Sorry! The requested user was not found for edit.'));
                    else if (result == -2)
                        $('#divMakeUserDialog-body').prepend(WarningMessageBox('Sorry! the <b>User Name</b> already exists, please choose another.'));
                    else if (result > 1) {
                        $('#divMakeUserDialog-body').prepend(SuccessMessageBox('Congratulations! The contact saved as user successfully. Now this contact will be able to login to @ConfigReader.SiteName'));
                        $('#ID').val(result);
                    }
                });
            }
        }

        function DeleteCinfrim(id, anchor) {
            _ContactID = id;
            _Anchor = anchor;
            $('#deleteDialog').modal('show');
            $('#deleteDialog-body').html('Are you sure you want to delete this contact?');
        }
        function DeleteContact() {
            ShowLoadingAnimation(false);
            Ajax('/Private/Contact/Delete/' + _ContactID, null, function (result) {
                if (result == 1) {
                    $('#deleteDialog-body').append(SuccessMessageBox('Contact Deleted Successfully.'));
                    $(_Anchor).closest('tr').remove();
                    HideLoadingAnimation();
                    setTimeout(function () { $('#deleteDialog').modal('hide'); }, 3000);
                }
                else {
                    $('#deleteDialog-body').prepend(WarningMessageBox('Sorry! Unable to delete the contact.'));
                }
            });
        }
    </script>

}